package first.niuke.simple;

import java.util.ArrayList;

/**
 * @ClassName NC58
 * @description:
 * @author: 荣燊
 * @create: 2021-06-02 22:19
 **/
public class NC58 {
    ArrayList<Integer> list = new ArrayList<>();

    // 搜索二叉树，其中有两个节点调换了位置，
    /**
     * 左子树上所有结点的值均小于它的根结点的值
     * 右子树上所有结点的值均大于它的根结点的值
     */
    public int[] findError (TreeNode root) {
        // write code here
        int[] result = new int[2];
        if (root == null) {
            return result;
        }
        dfs(root);
        int i = 0;
        for ( ; i<list.size()-1; i++) {
            if (list.get(i) > list.get(i+1)) {
                result[1] = list.get(i);
                break;
            }
        }
        for (int j=list.size()-1; j>=i; j--) {
            if (list.get(j) < list.get(j-1)) {
                result[0] = list.get(j);
                break;
            }
        }
        return result;
    }

    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        list.add(root.val);
        dfs(root.right);
    }

    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    }
}
